package tclp.gui.panels;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import javax.swing.*;
import org.jnativehook.keyboard.NativeKeyEvent;
import tclp.gui.GUIController;

/**
 *
 * @author Absatz Leoš
 */
public class MainPanel extends JPanel {

    private GUIController controller;
    private JTextArea areaKey;
    private JTextArea areaFraps;
    private JButton keyButton;
    private JButton frapsButton;
    private NativeKeyEvent activationKey;
    private JLabel status;

    public MainPanel(GUIController controller) {
        this.controller = controller;
        this.activationKey = controller.getActivationKey();

        initComponents();
    }

    private void initComponents() {
        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        // Label
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(10, 10, 10, 10);
        c.anchor = GridBagConstraints.NORTHWEST;
        c.weightx = 1;
        c.gridwidth = 3;
        JLabel label = new JLabel("Main Screen");
        this.add(label, c);


        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.insets = new Insets(0, 10, 0, 0);
        c.anchor = GridBagConstraints.WEST;
        JLabel labelKey = new JLabel("Activation Key: ");
        this.add(labelKey, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 1;
        c.anchor = GridBagConstraints.WEST;
        areaKey = new JTextArea();
        areaKey.setColumns(30);
        areaKey.setEnabled(false);
        setKeyText(activationKey);
        this.add(areaKey, c);

        c = new GridBagConstraints();
        c.gridx = 2;
        c.gridy = 1;
        c.anchor = GridBagConstraints.WEST;
        c.weightx = 1;
        c.insets = new Insets(0, 5, 0, 0);
        keyButton = new JButton("Change");
        keyButton.setSize(100, 25);
        this.add(keyButton, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.insets = new Insets(0, 10, 0, 0);
        c.anchor = GridBagConstraints.WEST;
        JLabel labelFraps = new JLabel("Fraps screenshot folder: ");
        this.add(labelFraps, c);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 2;
        c.anchor = GridBagConstraints.WEST;
        areaFraps = new JTextArea();
        areaFraps.setColumns(50);
        areaFraps.setEditable(false);
        areaFraps.setText(controller.getFrapsPath());
        this.add(areaFraps, c);

        c = new GridBagConstraints();
        c.gridx = 2;
        c.gridy = 2;
        c.anchor = GridBagConstraints.WEST;
        c.weightx = 1;
        c.insets = new Insets(0, 5, 0, 0);
        frapsButton = new JButton("Select");
        frapsButton.setSize(100, 25);
        this.add(frapsButton, c);
        
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.anchor = GridBagConstraints.WEST;
        c.weightx = 1;
        c.insets = new Insets(10, 10, 0, 0);
        status = new JLabel("NOT RUNNING");
        this.add(status, c);

        c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = 4;
        c.anchor = GridBagConstraints.NORTHWEST;
        c.weightx = 1;
        c.weighty = 1;
        c.gridwidth = 3;
        JPanel fillPanel = new JPanel();
        this.add(fillPanel, c);

        addListeners();
    }

    private void addListeners() {
        areaKey.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
            }

            public void keyPressed(KeyEvent e) {
                NativeKeyEvent keyEvent = controller.getKeyListener().getLastKeyPressed();
                setKeyText(keyEvent);
                if ((e.getKeyCode() != 16) && (e.getKeyCode() != 17) && (e.getKeyCode() != 18)) { // Shift, Ctrl, Alt
                    areaKey.setEnabled(false);
                    keyButton.setEnabled(true);
                    saveKeySettings(keyEvent);
                }
            }

            public void keyReleased(KeyEvent e) {
                // noop
            }
        });

        keyButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                keyButton.setEnabled(false);
                areaKey.setEnabled(true);
                areaKey.setEditable(false);
                areaKey.getCaret().setVisible(true);
                areaKey.setCaretPosition(0);
                areaKey.requestFocus();
            }
        });

        frapsButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int returnVal = chooser.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    saveFrapsSettings(chooser.getSelectedFile().getAbsolutePath());
                }
            }
        });
    }

    private void setKeyText(NativeKeyEvent e) {
        if (e == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        switch (e.getModifiers()) {
            case 0: // nothing
                break;
            case 1: // Shift
                sb.append("Shift+");
                break;
            case 2: // Ctrl
                sb.append("Ctrl+");
                break;
            case 3: // Ctrl+Shift
                sb.append("Ctrl+Shift+");
                break;
            case 8: // Alt
                sb.append("Alt+");
                break;
            case 9: // Alt+Shift
                sb.append("Alt+Shift+");
                break;
            case 10: // Ctrl+Alt
                sb.append("Ctrl+Alt+");
                break;
            case 11: // Ctrl+Alt+Shift
                sb.append("Ctrl+Alt+Shift+");
                break;
        }

        if ((e.getKeyCode() != 16) && (e.getKeyCode() != 17) && (e.getKeyCode() != 18)) { // Shift, Ctrl, Alt     
            sb.append(NativeKeyEvent.getKeyText(e.getKeyCode()));
        }

        areaKey.setText(sb.toString());
    }

    private void saveKeySettings(NativeKeyEvent e) {
        try {
            File settingsFile = new File(controller.getSettings().getActivationKeySettings());
            settingsFile.delete();
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(settingsFile));
            outputStream.writeObject(e);
            outputStream.close();
            this.activationKey = e;
            controller.setActivationKey(e);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error saving activation key!");
            System.out.println(ex);
            ex.printStackTrace();
        }
    }

    private void saveFrapsSettings(String path) {
        try {
            File settingsFile = new File(controller.getSettings().getFrapsPathSettings());
            settingsFile.delete();
            BufferedWriter writer = new BufferedWriter(new FileWriter(settingsFile));
            writer.write(path);
            writer.close();
            areaFraps.setText(path);
            controller.setFrapsPath(path);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error saving activation key!");
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
    
    public void setStatus(boolean running) {
        if (running) {
            status.setText("RUNNING");
        } else {
            status.setText("NOT RUNNING");
        }
    }
}
